<template>
  <div class="news-list w1160">
    <ul class="flex">
      <li v-for="item in newsList" :key="item._id">
        <router-link :to="`/detail/${item._id}`">
          <img :src="item.cover" width="390" height="220" alt="new" />
          <p class="title fz16">{{ item.title }}</p>
          <p class="data fz14">{{ item.updatedAt }}</p>
        </router-link>
      </li>
    </ul>
    <!-- 分页 -->
    <div class="flexcenter">
      <el-pagination
        v-model:current-page="paginationConfig.pageNumber"
        v-model:page-size="paginationConfig.pageSize"
        :page-sizes="[1, 2, 3]"
        background
        size="small"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationConfig.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getNewsList } from '@/api/news.js'
import { ref } from 'vue'
import { useRouter, onBeforeRouteUpdate } from 'vue-router'
defineOptions({ name: 'NewsList' })
const router = useRouter()
const newsList = ref([])
const paginationConfig = ref({
  pageNumber: 1,
  pageSize: 2,
  total: 0
})
// 获取新闻列表数据
const getNewsListData = async () => {
  try {
    const { data, pagination } = await getNewsList({
      pageNumber: paginationConfig.value.pageNumber,
      pageSize: paginationConfig.value.pageSize
    })
    newsList.value = data
    paginationConfig.value = pagination
  } catch (error) {
    console.log(error)
  }
}
getNewsListData()
// 改变每页显示条数
const handleSizeChange = async (value) => {
  paginationConfig.value.pageSize = value
  router.push({
    path: '/news',
    query: {
      pageNumber: paginationConfig.value.pageNumber,
      pageSize: value
    }
  })
}
// 改变当前页
const handleCurrentChange = async (value) => {
  paginationConfig.value.pageNumber = value
  router.push({
    path: '/news',
    query: {
      pageNumber: value,
      pageSize: paginationConfig.value.pageSize
    }
  })
}
// 监听路由变化
onBeforeRouteUpdate((to, from, next) => {
  const { pageNumber } = to.query
  const pageSize = paginationConfig.value.pageSize
  paginationConfig.value.pageNumber = parseInt(pageNumber) || 1
  paginationConfig.value.pageSize = parseInt(pageSize) || 2
  getNewsListData()
  next()
})
</script>

<style lang="scss" scoped>
.news-list {
  padding: 80px 0 50px;
  ul {
    min-height: 325px;
    padding-bottom: 90px;
  }
  .title {
    margin-top: 20px;
    padding-left: 20px;
    width: 390px;
    color: #333;
  }
  .data {
    padding-left: 20px;
    margin-top: 30px;
    color: #666;
  }
}
</style>
